package com.jt.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jt.entity.MeterageDict;
import com.jt.entity.MeterageTemperamentReportChildren;
import com.jt.entity.Meterage_ReportChildren;
import com.jt.mapper.UserMapper;
import com.jt.pojo.*;
import com.jt.service.UserService;
import com.jt.utils.JwtUtil;
import com.jt.vo.MenuAndRolesVo;
import com.jt.vo.RoleVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    public JwtUtil jwtUtil;

    @Override
    public User login(User user) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()).eq("password", user.getPassword()));
    }

    @Override
    public List<MenuAndRolesVo> getRoleList(String id) {
        return userMapper.getRoleList(id);
    }

    @Override
    public void exportWps(HttpServletResponse response) throws IOException {
        OutputStream ouputStream = null;
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建excel中的sheet
            HSSFSheet sheet = workbook.createSheet("气质分析报告");
            sheet.setColumnWidth(0, (short) 12000);
            sheet.setColumnWidth(1, (short) 12000);
            sheet.setColumnWidth(2, (short) 12000);
            sheet.setColumnWidth(3, (short) 12000);
            sheet.setColumnWidth(4, (short) 12000);
            sheet.setColumnWidth(5, (short) 12000);
            /*标题样式*/

            HSSFCellStyle headstyle = workbook.createCellStyle();
            headstyle.setAlignment(HorizontalAlignment.CENTER);   //设置居中样式
            headstyle.setVerticalAlignment(VerticalAlignment.CENTER);
            Font titleFont = workbook.createFont();/*字体*/
            titleFont.setFontHeightInPoints((short) 18);
            headstyle.setFont(titleFont);

            //创建标题合并行
            HSSFRow row0 = sheet.createRow(0);
            row0.setHeight((short) 900);// 设置行高
            HSSFCell cell = row0.createCell(0);
            cell.setCellValue(new HSSFRichTextString("中卫压气站(西气东输-线东段干线)气质分析报告"));
            cell.setCellStyle(headstyle);
            /*合并标题*/
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));


            /*第二行*/
            HSSFRow row1 = sheet.createRow(1);
            row1.setHeight((short) 700);

            HSSFCell row1cell0 = row1.createCell(0);
            row1cell0.setCellValue("取样地点: 宁夏 ");
            setAlignmentCellStyle(workbook, row1cell0, false);

            HSSFCell row1cell1 = row1.createCell(1);
            row1cell1.setCellValue("null");
            setAlignmentCellStyle(workbook, row1cell1, false);


            HSSFCell row1cell2 = row1.createCell(2);
            row1cell2.setCellValue("分析日期:  2024-11-30");
            setAlignmentCellStyle(workbook, row1cell2, false);

            HSSFCell row1cell3 = row1.createCell(3);
            row1cell3.setCellValue("null");
            setAlignmentCellStyle(workbook, row1cell3, false);


            HSSFCell row1cell4 = row1.createCell(4);
            row1cell4.setCellValue("编码:  3212313213 ");
            setAlignmentCellStyle(workbook, row1cell4, false);

            HSSFCell row1cell5 = row1.createCell(5);
            row1cell5.setCellValue("null");
            setAlignmentCellStyle(workbook, row1cell5, false);
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 1));
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 2, 3));
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 4, 6));
            /*第三行*/
            HSSFRow row2 = sheet.createRow(2);
            HSSFCell cell0 = row2.createCell(0);
            cell0.setCellValue("分析项目");
            setAlignmentCellStyle(workbook, cell0, false);

            HSSFCell cell1 = row2.createCell(1);
            cell1.setCellValue("烃类(摩尔分数)y%");
            setAlignmentCellStyle(workbook, cell1, false);

            /*站空位*/
            HSSFCell cell2 = row2.createCell(2);
            setAlignmentCellStyle(workbook, cell2, false);
            /*站空位*/
            HSSFCell cell3 = row2.createCell(3);
            setAlignmentCellStyle(workbook, cell3, false);

            HSSFCell cell4 = row2.createCell(4);
            cell4.setCellValue("分析项目");
            setAlignmentCellStyle(workbook, cell4, false);

            HSSFCell cell5 = row2.createCell(5);
            cell5.setCellValue("烃类(摩尔分数)y%");
            setAlignmentCellStyle(workbook, cell5, false);
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 5, 6));


            /*List<ReportChildren> list = new ArrayList<>();
            ReportChildren reportChildren1 = new ReportChildren();
            reportChildren1.setName("甲烷,乙烷");
            reportChildren1.setNumber(1);
            list.add(reportChildren1);

            ReportChildren reportChildren2 = new ReportChildren();
            reportChildren2.setName("甲烷2,乙烷2");
            reportChildren2.setNumber(2);
            list.add(reportChildren2);*/
//            List<MeterageTemperamentReportChildren> listPipeline = meterageTemperamentReportChildrenService.list(queryWrapper);
            //查詢字典
//            String dict = "QZFXBG";
//            List<MeterageDict> dictList = meterageEverdayManagementChildrenMapper.selectDistinct(dict);
            //封装list
            List<com.jt.entity.Meterage_ReportChildren> meterageReportChildrenList = meterageReportChildrenList(null, null);

            setRow(meterageReportChildrenList, sheet, workbook);
            response.addHeader("Content-Type", "application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + new String("气质分析报告".getBytes("ISO8859-1")));
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ouputStream.flush();
            ouputStream.close();
        }
    }

    @Override
    public void exportWps1(String id, HttpServletResponse response) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("/CKQualityReportApplyFor_file/分项分部工程质量报验表测试.docx");
        File file = classPathResource.getFile();
        String filename = file.getName();
        Map<String, Object> params = new HashMap<>();
        CKQualityReportApplyFor ckQualityReportApplyFor = new CKQualityReportApplyFor();
        ckQualityReportApplyFor.setUnitworksName("1111");
        ckQualityReportApplyFor.setFbworksCode("2222");
        ckQualityReportApplyFor.setJlUnitName("3333");
        params.put("fbunitname", ckQualityReportApplyFor.getUnitworksName());
        params.put("fbunitcode", ckQualityReportApplyFor.getFbworksCode());
        params.put("jlunit", ckQualityReportApplyFor.getJlUnitName());
        String newFileName = "new分项分部工程质量报验表.docx";
        XWPFDocument word = new XWPFDocument(new FileInputStream(file));
        /*处理段落*/
        List<XWPFParagraph> paragraphs = word.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            replaceInPara(paragraph, params);
        }
        /*处理表格*/
        Iterator<XWPFTable> tablesIterator = word.getTablesIterator();
        while (tablesIterator.hasNext()) {
            XWPFTable table = tablesIterator.next();
            List<XWPFTableRow> rows = table.getRows();
            for (XWPFTableRow row : rows) {
                List<XWPFTableCell> tableCells = row.getTableCells();
                for (XWPFTableCell cell : tableCells) {
                    List<XWPFParagraph> paragraphsNew = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphsNew) {
                        replaceInPara(paragraph, params);
                    }

                }
            }
        }
        response.setHeader("content-disposition", "attachment;filename=" + new String(filename.getBytes(), "ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        word.write(response.getOutputStream());
    }

    @Override
    public Result getInfo(String token) {
        System.out.println(token);
        User user = jwtUtil.tokenAsUser(token);
        if (!Objects.isNull(user)) {
            /*返回角色信息*/
            List<MenuAndRolesVo> menuAndRolesVoList = this.getRoleList(user.getId());
            if (Objects.isNull(menuAndRolesVoList)) {
                return Result.error("角色为null");
            }
            RoleVo roleVo = new RoleVo();
            List<Menu> menuList = new ArrayList<>();
            List<String> roleList = new ArrayList<>();
            for (MenuAndRolesVo menuAndRolesVo : menuAndRolesVoList) {
                Menu menu = new Menu();
                BeanUtils.copyProperties(menuAndRolesVo, menu);
                Meta meta = new Meta();
                meta.setIcon(menuAndRolesVo.getIcon());
                meta.setTitle(menuAndRolesVo.getTitle());
                menu.setMeta(meta);
                if (menuAndRolesVo.getAlwaysShow().equals("0")) {
                    menu.setAlwaysShow(false);
                } else {
                    menu.setAlwaysShow(true);
                }
                if (menuAndRolesVo.getHidden().equals("0")) {
                    menu.setHidden(false);
                } else {
                    menu.setHidden(true);
                }
                menuList.add(menu);
                if (!roleList.contains(menuAndRolesVo.getRoleName()))
                    roleList.add(menuAndRolesVo.getRoleName());
            }
            List<Menu> parentList = menuList.stream().filter(a -> a.getParent().equals("0")).collect(Collectors.toList());
            getChildrenList(menuList, parentList);
            roleVo.setMenuList(parentList);
            roleVo.setRoles(roleList);
            if (roleList.contains("admin")) {
                roleVo.setSuperAdmin(true);
            }
            return Result.success(roleVo);
        }
        return Result.error("用户为null");
    }

    private void getChildrenList(List<Menu> allmenuList, List<Menu> parentList) {
        if (!CollectionUtils.isEmpty(parentList)) {
            parentList.forEach(parentOne -> {
                List<Menu> childrenList = allmenuList.stream().filter(a -> parentOne.getId().equals(a.getParent())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(childrenList)) {
                    parentOne.setChildren(childrenList);
                    getChildrenList(allmenuList, childrenList);
                }
            });
        }
    }

    public static void setRow(List<Meterage_ReportChildren> list, HSSFSheet sheet, HSSFWorkbook workbook) {
        for (Meterage_ReportChildren item : list) {
            if (item.getNumber() < 9) {
                String[] split = item.getName().split(",");
                HSSFRow row = sheet.createRow(item.getNumber() + 2);
                HSSFCell cell0 = row.createCell(0);
                cell0.setCellValue(split[0]);
                setAlignmentCellStyle(workbook, cell0, true);

                HSSFCell cell1 = row.createCell(1);
                cell1.setCellValue("null");
                setAlignmentCellStyle(workbook, cell1, false);

                /*站空位*/
                HSSFCell cell2 = row.createCell(2);
                setAlignmentCellStyle(workbook, cell2, false);
                /*站空位*/
                HSSFCell cell3 = row.createCell(3);
                setAlignmentCellStyle(workbook, cell3, false);
                if (item.getNumber() == 7 || item.getNumber() == 8) {
                    HSSFCell cell4 = row.createCell(4);
                    cell4.setCellValue(split[1]);
                    setAlignmentCellStyle(workbook, cell4, true);

                    HSSFCell cell5 = row.createCell(5);
                    cell5.setCellValue("");
                    setAlignmentCellStyle(workbook, cell5, false);
                } else {
                    HSSFCell cell4 = row.createCell(4);
                    cell4.setCellValue(split[1]);
                    setAlignmentCellStyle(workbook, cell4, true);

                    HSSFCell cell5 = row.createCell(5);
                    cell5.setCellValue("null");
                    setAlignmentCellStyle(workbook, cell5, false);
                }
                sheet.addMergedRegion(new CellRangeAddress(item.getNumber() + 2, item.getNumber() + 2, 5, 6));
            } else {
                String[] split = item.getName().split(",");
                HSSFRow row = sheet.createRow(item.getNumber() + 2);
                HSSFCell cell0 = row.createCell(0);
                cell0.setCellValue(split[0]);
                setAlignmentCellStyle(workbook, cell0, true);

                HSSFCell cell1 = row.createCell(1);
                setAlignmentCellStyle(workbook, cell1, false);

                /*站空位*/
                HSSFCell cell2 = row.createCell(2);
                cell2.setCellValue("null");
                setAlignmentCellStyle(workbook, cell2, false);
                /*站空位*/
                HSSFCell cell3 = row.createCell(3);
                setAlignmentCellStyle(workbook, cell3, false);
                /*站空位*/
                HSSFCell cell4 = row.createCell(4);

                setAlignmentCellStyle(workbook, cell4, false);
                /*站空位*/
                HSSFCell cell5 = row.createCell(5);

                setAlignmentCellStyle(workbook, cell5, false);
                sheet.addMergedRegion(new CellRangeAddress(item.getNumber() + 2, item.getNumber() + 2, 0, 1));
                sheet.addMergedRegion(new CellRangeAddress(item.getNumber() + 2, item.getNumber() + 2, 2, 6));
            }
        }

    }

    /*列表样式*/
    public static void setAlignmentCellStyle(HSSFWorkbook workbook, HSSFCell cell, boolean isTitle) {
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);   //设置居中样式
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        if (isTitle) {
            /*颜色*/
            cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        } else {
            HSSFFont font = workbook.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 15);
            cellStyle.setFont(font);
        }
        cell.setCellStyle(cellStyle);
    }

    /*封装list*/
    private List<com.jt.entity.Meterage_ReportChildren> meterageReportChildrenList(List<MeterageTemperamentReportChildren> listResult, List<MeterageDict> dictList) {
        List<com.jt.entity.Meterage_ReportChildren> list = new ArrayList<>();
        com.jt.entity.Meterage_ReportChildren reportChildrenOne = new com.jt.entity.Meterage_ReportChildren();
        reportChildrenOne.setName("甲烷（CH4）,氮气（N2）");
        reportChildrenOne.setNumber(1);
        list.add(reportChildrenOne);
        com.jt.entity.Meterage_ReportChildren reportChildrenTwo = new com.jt.entity.Meterage_ReportChildren();
        reportChildrenTwo.setName("乙烷（C2H6）,二氧化碳（CO2）");
        reportChildrenTwo.setNumber(2);
        list.add(reportChildrenTwo);
        com.jt.entity.Meterage_ReportChildren reportChildrenThread = new com.jt.entity.Meterage_ReportChildren();
        reportChildrenThread.setName("丙烷（C3H6）,氢气（H2）");
        reportChildrenThread.setNumber(3);
        list.add(reportChildrenThread);
        com.jt.entity.Meterage_ReportChildren reportChildrenFour = new com.jt.entity.Meterage_ReportChildren();
        reportChildrenFour.setName("异丁烷（i-C4H10）,一氧化碳（CO）");
        reportChildrenFour.setNumber(4);
        list.add(reportChildrenFour);
        com.jt.entity.Meterage_ReportChildren reportChildrenFive = new com.jt.entity.Meterage_ReportChildren();
        reportChildrenFive.setName("正丁烷（n-C4H10）,氩气（Ar）");
        reportChildrenFive.setNumber(5);
        list.add(reportChildrenFive);
        com.jt.entity.Meterage_ReportChildren reportChildrenSex = new com.jt.entity.Meterage_ReportChildren();
        reportChildrenSex.setName("异戊烷（i-C5H12）,新戊烷C（CH3）4");
        reportChildrenSex.setNumber(6);
        list.add(reportChildrenSex);
        com.jt.entity.Meterage_ReportChildren reportChildrenSeven = new com.jt.entity.Meterage_ReportChildren();
        reportChildrenSeven.setName("正戊烷（n-C5H12）, ");
        reportChildrenSeven.setNumber(7);
        list.add(reportChildrenSeven);
        com.jt.entity.Meterage_ReportChildren reportChildrenEle = new com.jt.entity.Meterage_ReportChildren();
        reportChildrenEle.setName("C6+, ");
        reportChildrenEle.setNumber(8);
        list.add(reportChildrenEle);
        /*特殊1*/
        Meterage_ReportChildren reportChildrenA = new Meterage_ReportChildren();
        reportChildrenA.setName("H2S（mg/m³）, ");
        reportChildrenA.setNumber(9);
        list.add(reportChildrenA);
        Meterage_ReportChildren reportChildrenB = new Meterage_ReportChildren();
        reportChildrenB.setName("总硫（以硫计）（mg/m³）, ");
        reportChildrenB.setNumber(10);
        list.add(reportChildrenB);
        Meterage_ReportChildren reportChildrenC = new Meterage_ReportChildren();
        reportChildrenC.setName("水露点（℃）, ");
        reportChildrenC.setNumber(11);
        list.add(reportChildrenC);
        Meterage_ReportChildren reportChildrenD = new Meterage_ReportChildren();
        reportChildrenD.setName("烃露点（℃）, ");
        reportChildrenD.setNumber(12);
        list.add(reportChildrenD);
        Meterage_ReportChildren reportChildrenE = new Meterage_ReportChildren();
        reportChildrenE.setName("绝对密度, ");
        reportChildrenE.setNumber(13);
        list.add(reportChildrenE);
        Meterage_ReportChildren reportChildrenF = new Meterage_ReportChildren();
        reportChildrenF.setName("高位发热量（MJ/m³）, ");
        reportChildrenF.setNumber(14);
        list.add(reportChildrenF);
        Meterage_ReportChildren reportChildrenG = new Meterage_ReportChildren();
        reportChildrenG.setName("低位发热量（MJ/m³）, ");
        reportChildrenG.setNumber(15);
        list.add(reportChildrenG);
        return list;
    }

    public static void replaceInPara(XWPFParagraph para, Map<String, Object> params) {
        List<XWPFRun> runs = para.getRuns();
        for (XWPFRun run : runs) {
            String text = run.getText(0);
            for (String key : params.keySet()) {
                if (text.contains(key)) {
                    run.setText(text.replaceAll(key, (String) params.get(key)), 0);
                }
            }
        }
    }
}
